
import router from '../router/index.js'
import Vue from 'vue'
const { programmeFlag } = require('../settings.js')

/**
 * Parse the time to string
 * @source {(Object|Array)} time
 * @returns {Object}
 */
// 深拷贝
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    // throw new Error('error arguments', 'deepClone')
    return
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
// return JSON.parse(JSON.stringify(source || []))
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  if (!time) return ''
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if (time.indexOf('T')) {
        time = time.replace('T', ' ')
      }
      if (time.indexOf('Z')) {
        time = time.replace('Z', ' ')
      }
      if (/^[0-9]+$/.test(time)) {
        time = parseInt(time)
      } else {
        time = time.replace(/-/g, '/') // 处理safari与ie兼容
      }
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, ' ') +
      '"}'
  )
}
/**
 * JSON对象转formData
 * @param {Object} JSON对象
  */
export function json2FormData(params) {
  const formData = new FormData()
  Object.keys(params).forEach((key) => {
    formData.append(key, params[key])
  })
  return formData
}

export function createDownload(res, fixedFileName) {
  const data = res
  let fileName
  if (fixedFileName) {
    fileName = `${decodeURIComponent(fixedFileName)}${parseTime(new Date(), '{y}{m}{d}{h}{i}{s}')}.xlsx`
  } else {
    fileName = res.headers['content-disposition']
    fileName = fileName.split(';')[1].split('filename=')[1]
    const fileNameUnicode = res.headers['content-disposition'].split('filename*=')[1]
    if (fileNameUnicode) { // 当存在 filename* 时，取filename* 并进行解码（为了解决中文乱码问题）
      fileName = decodeURIComponent(fileNameUnicode.split("''")[1])
    } else {
      fileName = decodeURIComponent(fileName)
    }
  }

  const blob = new Blob([data])
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, fileName)
  } else {
    const link = document.createElement('a')
    link.download = decodeURI(fileName)
    link.href = URL.createObjectURL(blob)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }

  /* const blob = new Blob([data])
  const link = document.createElement('a')
  const evt = document.createEvent('HTMLEvents')
  evt.initEvent('click', false, false)
  link.href = URL.createObjectURL(blob)
  link.download = decodeURI(fileName)
  link.style.display = 'none'
  document.body.appendChild(link)
  link.click()
  window.URL.revokeObjectURL(link.href) */
}

// 判断所选日期是否大于当前日期
export function judgeDate(tomodifyDate) {
  const selectTime = tomodifyDate + ' 00:00:00'
  return new Date().getTime() - new Date(selectTime).getTime()
}

// 日期年月日格式化
export function formatFullYear(date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return `${year}年${month > 9 ? month : ('0' + month)}月${day > 9 ? day : ('0' + day)}日`
}

/**
 * 判断是否为IE
 */
export function detectIE() {
  var ua = window.navigator.userAgent
  var msie = ua.indexOf('MSIE ')
  if (msie > 0) {
    // IE 10 or older => return version number
    return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10)
  }

  var trident = ua.indexOf('Trident/')
  if (trident > 0) {
    // IE 11 => return version number
    var rv = ua.indexOf('rv:')
    return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10)
  }

  var edge = ua.indexOf('Edge/')
  if (edge > 0) {
    // Edge (IE 12+) => return version number
    return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10)
  }

  // other browser
  return false
}
/*
 *序列化query
 */
export const serialize = data => {
  const list = []
  Object.keys(data).forEach(ele => {
    list.push(`${ele}=${data[ele]}`)
  })
  return list.join('&')
}
/**
*打开新页面，本地开路由，线上开页签
* @param {(string)} path:路径
* @param {(Object)} query:参数
* @param {(string)} pageName:页签名称
* @param {(string)} menuCode:菜单编码
*/
export function openPage(path, query, pageName, menuCode) {
  if (process.env.NODE_ENV === 'development') {
    router.push({
      path: path,
      query
    })
  } else {
    window.parent.postMessage({
      flag: 'addtag',
      extraData: {
        url: programmeFlag + path.substring(1),
        title: pageName,
        query: query ? '&' + serialize(query) : '',
        menuCode: menuCode
      }
    }, '*')
  }
}

export function otherFiltersItem(key, value, operator, id) {
  if (id === undefined) {
    id = Math.floor(Math.random() * 0xffffff).toString(16)
  }
  return {
    property: key,
    value,
    operator,
    id
  }
}
export function fileDown(url, name) {
  const a = document.createElement('a')
  a.href = url
  a.download = name
  a.target = '_blank'
  a.click()
}
/**
 * 防抖
 * @param {*} fn
 * @param {*} delay
 * @param {*} ctx
 * @returns
 */
export function debounce(fn, delay = 200, ctx) {
  let id = null
  let _reject = null
  return (...args) => {
    if (_reject != null) {
      _reject('防抖')
      _reject = null
    }
    if (id != null) {
      clearTimeout(id)
      id = null
    }
    return new Promise((resolve, reject) => {
      _reject = reject
      id = setTimeout(() => {
        const r = fn.apply(ctx, args)
        if (r instanceof Promise) {
          r.then(re => resolve(re)).catch(e => reject(e))
        } else {
          resolve(r)
        }
        _reject = null
        id = null
      }, delay)
    })
  }
}
// url 拼接 没有前缀的话 拼接 有前缀不拼接
export function filterURL(url) {
  // url 为固定的参数 如果url为相对地址,则返回绝对地址
  if (url) {
    const isHttps = url.indexOf('https://')
    const isHttp = url.indexOf('http://')

    if (isHttps > -1 || isHttp > -1) {
      return url
    } else {
      return `${process.env.VUE_APP_IMG_PREFIX}${url}`
    }
  }
}
// 数据字典格式化数据
export function formaterData(arr, value, labelName = 'dictName', labelValue = 'dictCode') {
  if (!value || !arr) {
    return value || ''
  }
  let list = []
  if (typeof (value) === 'string') {
    list = value.split(',')
  } else {
    list = value
  }
  const temp = []
  arr.forEach((item) => {
    const flag = list.some(v => v === item[labelValue])
    if (flag) {
      temp.push(item[labelName])
    }
  })
  return temp.toString() || value
}
/**
 * 合并obj
 * @param  {...any} args
 */
export function concatObj(...args) {
  const t = {}
  for (const arg of args) {
    for (const [key, value] of Object.entries(arg || {})) {
      if ((t[key] === undefined || t[key] === '' || t[key] === null || t[key] === 'null') && (value !== undefined && value !== null && value !== '' && value !== 'null')) {
        t[key] = value
      }
    }
  }
  return t
}
/**
 * 向下查找
 * @param {*} children
 * @param {*} name
 * @returns
 */
export function findChildComponent(children, name) {
  let t
  for (const c of children) {
    if (c.$options.name === name) {
      t = c
      break
    } else if (c.$children && c.$children instanceof Array) {
      t = findChildComponent(c.$children, name)
      if (t) {
        break
      }
    }
  }
  return t
}
/**
 * 向上查找
 * @param {*} parent
 * @param {*} name
 * @returns
 */
export function findParentComponent(parent, name) {
  if (parent && parent.$options && parent.$options.name === name) {
    return parent
  } else if (parent.$parent) {
    const t = findParentComponent(parent.$parent, name)
    if (t) {
      return t
    }
  }
}

export function split(v, sep = ',') {
  if (v === undefined || v === null) {
    return []
  }
  if (v instanceof Array) {
    return v.filter(e => e !== '' && e !== undefined && e !== null)
  }
  return v.toString().split(sep).filter(e => e !== '' && e !== undefined && e !== null)
}
Object.defineProperty(Vue.prototype, '$split', { value: split })
Object.defineProperty(Vue.prototype, '$toString', { value: function(v) {
  if (v === undefined || v === null) {
    return ''
  }
  return v.toString()
} })
Object.defineProperty(Vue.prototype, '$eqSet', { value: function(a1, a2) {
  a1 = new Set(split(a1))
  a2 = new Set(split(a2))
  const eq = []
  a1.forEach(e => {
    eq.push(a2.has(e))
  })
  a2.forEach(e => {
    eq.push(a1.has(e))
  })
  return eq.every(e => e)
} })
Object.defineProperty(Vue.prototype, '$gtZero', { value: function(v) {
  if (v === undefined || v === null || v === 0 || v === '0') {
    return false
  }
  return parseFloat(v) > 0
} })
Object.defineProperty(Vue.prototype, '$gtEmpty', { value: function(v) {
  if (v === undefined || v === null) {
    return false
  }
  return parseFloat(v) >= 0
} })
Object.defineProperty(Vue.prototype, '$isTrue', { value: function(v, ...args) {
  return args.some(e => v === e)
} })
Object.defineProperty(Vue.prototype, '$toNumber', { value: function(v) {
  const t = parseFloat(v)
  if (isNaN(t)) {
    return 0
  }
  return t
} })

Object.defineProperty(Vue.prototype, '$isEmpty', { value: function(v) {
  return v === undefined || v === null || v === ''
} })

/**
 * 获取两个月份之间的具体月份
 * @param {*} start YYYY-MM
 * @param {*} end YYYY-MM
 * @returns
 */
export function monthRange(start, end) {
  const result = []
  const newResult = []
  const starts = start.split('-')
  const ends = end.split('-')
  let staYear = parseInt(starts[0])
  let staMon = parseInt(starts[1])
  const endYear = parseInt(ends[0])
  const endMon = parseInt(ends[1])
  while (staYear <= endYear) {
    if (staYear === endYear) {
      while (staMon < endMon) {
        staMon++
        result.push({ year: staYear, month: staMon })
      }
      staYear++
    } else {
      staMon++
      if (staMon > 12) {
        staMon = 1
        staYear++
      }
      result.push({ year: staYear, month: staMon })
    }
  }

  for (let i = 0; i < result.length; i++) {
    const year = result[i].year
    const monthinit = result[i].month
    let month = ''
    // 补'0'操作
    if (monthinit < 10) {
      month = '0' + monthinit
    } else {
      month = monthinit + ''
    }
    const ym = year + '-' + month
    newResult.push(ym)
  }
  newResult.unshift(start)

  return newResult
}
